<template>
  <div>
     <div class="wrapper">
      <!-- 面包屑 -->
      <div class="c1">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px">
          <el-breadcrumb-item :to="{ path: '/backstage/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>求职信息列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="add_style"><el-link icon="el-icon-edit" type="primary" @click="addJobInfo">添加求职信息</el-link></div>
    </div>
    <el-card shadow="hover">
       <!-- 搜索表单 -->
      <el-form :model="ruleForm" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="求职用户" prop="huntUser">
              <el-input v-model="ruleForm.huntUser" prefix-icon="el-icon-coordinate" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="求职岗位" prop="posName">
              <el-input prefix-icon="el-icon-s-ticket" v-model="ruleForm.posName" clearable ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="firstRow_thirdCol_style">
            <a @click="toggleAdvanced">
                {{ advanced ? '收起' : '展开' }}
                <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
            </a>
            <el-button class="querybtn" type="primary" icon="el-icon-search" @click="submitForm('ruleForm')">查询</el-button>
            <el-button icon="el-icon-help" @click="resetForm('ruleForm')">重置</el-button>
          </el-col>
        </el-row>
        
        <el-collapse-transition>
          <div v-show="advanced">
            <el-row>
              <el-col :span="8">
                <el-form-item label="婚姻状态" prop="maritalStatus">
                  <el-select v-model="ruleForm.maritalStatus" placeholder="请选择" clearable>
                    <el-option label="已婚" value="1"></el-option>
                    <el-option label="未婚" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="性别要求" prop="gender">
                  <el-select v-model="ruleForm.gender" placeholder="请选择" clearable>
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="0"></el-option>
                    <el-option label="无限制" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </el-form>

      <el-table :data="tableData" id="tabledataView">
        <el-table-column
          label="用户"
          prop="huntUser"
          align="center"
          width="120">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>性别: {{ scope.row.gender }}</p>
              <p>电话: {{ scope.row.phone }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.huntUser }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column
          prop="posName"
          label="岗位"
          align="center"
          width="120">
        </el-table-column>

        <el-table-column
          prop="salary"
          label="期望薪资"
          align="center"
          width="100">
        </el-table-column>

        <el-table-column
          prop="maritalStatus"
          label="婚姻状态"
          align="center"
          width="120">
        </el-table-column>

        <el-table-column
          sortable
          prop="worktime"
          label="上班时间"
          align="center"
          width="120">
        </el-table-column>

        <el-table-column
          prop="resume"
          label="个人简历"
          align="center"
          width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.experience == null"
              size="mini"
              type="primary"
              plain
              @click="downLoadPersonalIntroduction(scope.row)"
            >下载
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="info"
              plain
              @click="detail(scope.$index, scope.row)">详情</el-button>
            <el-button
              size="mini"
              type="primary"
              plain
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-popconfirm confirm-button-text='确定'
                          cancel-button-text='取消'
                          icon="el-icon-info"
                          icon-color="red"
                          title="确定删除这个求职信息吗？"
                          @confirm="delleteJobInfoFunc(scope.row)">
              <el-button type="danger" size="mini" slot="reference" plain>删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div>
           <!-- 分页 -->
          <el-pagination
            style="float:left;"
            background
            layout="prev, pager, next"
            :page-size="pageRow"
            :total="total"
            @current-change="page">
          </el-pagination>
           <span class="daochu_style">  
             <el-button
              size="mini"
              type="primary"
              plain
              @click="daochufunc"
            >
              导出
            </el-button></span>
      </div>
    </el-card>

    <!-- 详情页面dialog -->
    <job-info-detail :show.sync="show" v-bind:detailRow="detailRow"/>

     <!-- 点击编辑或添加弹出dialog -->
    <job-info-add-or-edit-dialog  :show.sync="showEdit" v-bind:detailRow="detailRow"/>

  </div>
</template>

<script>

// 导出为word的引入
import JSZipUtils from 'jszip-utils';
import JSZip from 'jszip';
import docxtemplater from 'docxtemplater';
import ImageModule from "docxtemplater-image-module-free";
import { saveAs } from 'file-saver';

import JobInfoDetail from './JobInfoDetail.vue';
import JobInfoAddOrEditDialog from './JobInfoAddOrEditDialog.vue';
import {getStore} from "../../../storage/storage";
import { downloadPDF } from "../../../utils/html2canvas";
import { queryClickUserResume } from "../../../api/personalApi/index";
// import { downLoadAsExcel } from "../../../utils/exportExcel";
import { getJobInfoListApi,getDownload,download,delJobInfoByAid } from "../../../api/jobInfoManageApi/index";
export default {
  name: "JobInfoList",
  components:{ JobInfoDetail,JobInfoAddOrEditDialog },
  data(){
    return{
      advanced: true, // 控制表单的收起和展开
      ruleForm: {
        huntUser: '',
        posName: '',
        maritalStatus: '',
        gender: '',
      },
      tableData: [],
      pageRow: 5,
      total: 100,
      show: false, // 详情页面弹窗显示
      showEdit: false, // 点击编辑弹窗显示
      detailRow: {}, // 点击详情之后每一行的数据 是个对象
    }
  },
  methods:{

    // 提交表单
    submitForm(){
       // 发送请求，返回列表数据
      const searchFormParams = {
        account: getStore("account"),
        huntUser: this.ruleForm.huntUser,
        posName: this.ruleForm.posName,
        maritalStatus: this.ruleForm.maritalStatus ? parseInt(this.ruleForm.maritalStatus) : '',
        gender: this.ruleForm.gender ? parseInt(this.ruleForm.gender) : '',
        page: 1, // 页面初始化完成之后默认查询第一页
        pageRow: this.pageRow, // 每页行数
      }
      getJobInfoListApi(searchFormParams).then(res=>{
        this.tableData = res.data.data.jobInfoList;
        this.total = res.data.data.totalNum
      })
    },

    // 点击展开或者折叠改变状态
    toggleAdvanced(){
      this.advanced = !this.advanced
    },
     // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.submitForm();
    },
    page(currentPage){
      // 发送请求，返回列表数据
       const searchFormParams = {
        account: getStore("account"),
        huntUser: this.ruleForm.huntUser,
        posName: this.ruleForm.posName,
        maritalStatus: this.ruleForm.maritalStatus ? parseInt(this.ruleForm.maritalStatus) : '',
        gender: this.ruleForm.gender ? parseInt(this.ruleForm.gender) : '',
        page: currentPage, // 页面初始化完成之后默认查询第一页
        pageRow: this.pageRow, // 每页行数
      }
      getJobInfoListApi(searchFormParams).then(res=>{
        this.tableData = res.data.data.jobInfoList;
        this.total = res.data.data.totalNum
      })
    },
    // 点击详情
    detail(index,row){
      this.show = true;
      this.detailRow = row;
      console.log(this.detailRow);
    },
    // 添加
    addJobInfo(){
      this.showEdit = true;
    },
    // 编辑
    handleEdit(index,row){
      this.showEdit = true;
      this.detailRow = row;
      // console.log(row);
    },
    // 删除
    delleteJobInfoFunc(row){
      const params = {
        jobInfoAid: row.aid,
      }
      delJobInfoByAid(params).then(res=>{
        this.$message({
            message: res.data.message,
            type: 'success',
            duration: 800,
        });
        setTimeout(() => {
          this.$router.go(0);
        }, 800);
      })
    },

    // 下载个人简历
    downLoadPersonalIntroduction(row){

      const form = {
        avatar: '', //简历头像
        name: '', // 姓名
        currentIdentity: '', // 当前身份
        sex: '', // 性别（返回1：男；返回0：女）
        age: '', // 年龄
        city: '', // 城市
        outlook: '', // 政治面貌
        phone: '', // 手机号
        email: '', // 邮箱
        huntjobState: '', // 求职状态
        expectWork: '', // 意向工作
        expectSalary: '', // 期望薪资
        expectCity: '', // 期望工作的城市
        expectIndustry: '', // 期望的行业
        highestEducation: '', // 最高学历
        school: '', // 毕业院校
        major: '', // 所学专业
        companyName: '', // 工作或实习的公司名称
        companyPosition: '', // 实习或工作的公司岗位
        internshipWorkSalary: '', // 实习或工作的薪资
        companyType: '', // 实习或工作的公司类别
        internshipWorkDescription: '', //实习或工作的时候负责的工作
        projectName: '', // 项目名称
        projectDescription: '', // 项目描述
        englishLevel: '', // 英语等级
        skillDescription: '', // 技能描述
        certificate: '', // 证书
        selfEvaluation: '', // 自我评价
        personalAdvantange: '', // 个人优势
      };
      
      const params = {
        userJobAid: row.aid,
      }
      // 查询个人简历信息
      queryClickUserResume(params).then(res=>{
        // console.log(res);
        if(res.data.data === null){
          this.$message({
            message: '该用户该没有简历！',
            type: 'info',
            duration: 600,
          })
        }else{
          form.avatar = res.data.data.avatar ? res.data.data.avatar : 'https://recruitment-files.oss-cn-chengdu.aliyuncs.com/user/hr1.jpg';
          form.name = res.data.data.name;
          form.currentIdentity = (res.data.data.currentIdentity === null) ? '身份未知' : res.data.data.currentIdentity;
          form.sex = res.data.data.gender === 0 ? '女' : '男';
          form.age = new Date().getFullYear() - parseInt(res.data.data.birth.substr(0,4));
          form.city = res.data.data.city === null ? '未知' : res.data.data.city.substr(2,4);
          form.outlook = res.data.data.outlook === null ? '未知' : res.data.data.outlook;
          form.phone = res.data.data.phone ? res.data.data.phone : '未知';
          form.email = res.data.data.email ? res.data.data.email : '未知';
          form.huntjobState = res.data.data.huntjobState ? res.data.data.huntjobState : '未知';
          form.expectWork = res.data.data.expectWork ? res.data.data.expectWork : '未知';
          form.expectSalary = res.data.data.expectSalary ? res.data.data.expectSalary : '未知';
          form.expectCity = res.data.data.expectCity ? res.data.data.expectCity : '未知';
          form.expectIndustry = res.data.data.expectIndustry ? res.data.data.expectIndustry : '未知';
          form.highestEducation = res.data.data.highestEducation ? res.data.data.highestEducation : '未知';
          form.school = res.data.data.school ? res.data.data.school : '未知';
          form.major = res.data.data.major ? res.data.data.major : '未知';
          form.companyName = res.data.data.companyName ? res.data.data.companyName : '未知';
          form.companyPosition = res.data.data.companyPosition ? res.data.data.companyPosition : '未知';
          form.internshipWorkSalary = res.data.data.internshipWorkSalary ? res.data.data.internshipWorkSalary : '未知';
          form.companyType = res.data.data.companyType ? res.data.data.companyType : '未知';
          form.internshipWorkDescription = res.data.data.internshipWorkDescription ? res.data.data.internshipWorkDescription : '未知';
          form.projectName = res.data.data.projectName ? res.data.data.projectName : '未知';
          form.projectDescription = res.data.data.projectDescription ? res.data.data.projectDescription : '未知';
          form.englishLevel = res.data.data.englishLevel ? res.data.data.englishLevel : '未知';
          form.skillDescription = res.data.data.skillDescription ? res.data.data.skillDescription : '未知';
          form.certificate = res.data.data.certificate ? res.data.data.certificate : '未知';
          form.personalAdvantange = res.data.data.personalAdvantange ? res.data.data.personalAdvantange : '未知';
          form.selfEvaluation = res.data.data.selfEvaluation ? res.data.data.selfEvaluation : '未知';
          // 读取并获得模板文件的二进制内容
          JSZipUtils.getBinaryContent("input.docx", function(error, content) {
            // input.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
            // 抛出异常
            if (error) {
              throw error;
            }  
            // 创建一个JSZip实例，内容为模板的内容
            let zip = new JSZip(content);
            // 创建并加载docxtemplater实例对象
            let doc = new docxtemplater();
            // 设置模板变量的值
            doc.loadZip(zip);
            doc.setData({
              ...form,
            });

            try {
              // 用模板变量的值替换所有模板变量
              doc.render();
            } catch (error) {
              // 抛出异常
              throw error;
            }
            
            // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
            let out = doc.getZip().generate({
              type: "blob",
              mimeType:
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            });
            // 将目标文件对象保存为目标类型的文件，并命名
            saveAs(out, form.name + "_" + "简历.docx");
          });
        }        
      });
    },

    exportExcelfunc(){
      downLoadAsExcel(document.querySelector("#tabledataView"));
    },

    daochufunc(){
      downloadPDF(document.querySelector('#tabledataView'), '求职信息表')
    }

  },
  created(){
    // 发送请求，返回列表数据
    const searchFormParams = {
        account: getStore("account"),
        huntUser: this.ruleForm.huntUser,
        posName: this.ruleForm.posName,
        maritalStatus: this.ruleForm.maritalStatus,
        gender: this.ruleForm.gender,
        page: 1, // 页面初始化完成之后默认查询第一页
        pageRow: this.pageRow, // 每页行数
    }
    getJobInfoListApi(searchFormParams).then(res=>{
      console.log(res);
      this.tableData = res.data.data.jobInfoList;
      this.total = res.data.data.totalNum
    })
  }
}
</script>

<style scoped>
.add_style{
  float: right;
}
.wrapper{
  overflow: auto;
}
.c1{
  float: left;
}
.firstRow_thirdCol_style{
  padding-left: 40px;
}
.querybtn{
  margin-left: 10px;
}
.daochu_style{
  display: flex;
  float: right;
}
</style>